<script lang="tsx">
import { defineComponent, ref, h, compile, computed, watchEffect } from 'vue';
import {
  IconHome,
  IconCalendar,
  IconCaretRight,
  IconCaretLeft
} from '@arco-design/web-vue/es/icon';
import { useRoute, useRouter, RouteRecordRaw } from 'vue-router';
import type { RouteMeta } from 'vue-router';
import { useAppStore, useMenusStore } from '@/store';
import { listenerRouteChange } from '@/utils/route-listener';
import { openWindow, regexUrl } from '@/utils';
import useMenuTree from './use-menu-tree';
import IconFont from '@/components/IconFont/index.vue';

export default defineComponent({
  emit: ['collapse'],
  setup() {
    const appStore = useAppStore();
    const menusStore = useMenusStore();
    const router = useRouter();
    const route = useRoute();
    const { menuTree } = useMenuTree();
    // const menuTree1: any = computed(() => menuTree.value);
    const collapsed = computed({
      get() {
        if (appStore.device === 'desktop') return appStore.menuCollapse;
        return false;
      },
      set(value: boolean) {
        appStore.updateSettings({ menuCollapse: value });
      }
    });

    const openKeys = ref<string[]>([]);
    const selectedKey = ref<string[]>([]);

    const goto = (item: RouteRecordRaw) => {
      // Open external link 打开外部链接
      if (regexUrl.test(item.path)) {
        openWindow(item.path);
        selectedKey.value = [item.name as string];
        return;
      }
      // Eliminate external link side effects 消除外部链接的副作用
      const { hideInMenu, activeMenu } = item.meta as RouteMeta;
      if (route.name === item.name && !hideInMenu && !activeMenu) {
        selectedKey.value = [item.name as string];
        return;
      }
      // Trigger router change 触发路由器更改
      router.push({
        name: item.name
      });
    };
    // 查找打开的菜单的key
    const findMenuOpenKeys = (name: string) => {
      const result: string[] = [];
      let isFind = false;
      const backtrack = (
        item: RouteRecordRaw,
        keys: string[],
        target: string
      ) => {
        if (item.name === target) {
          isFind = true;
          result.push(...keys, item.name as string);
          return;
        }
        if (item.children?.length) {
          item.children?.forEach((el) => {
            backtrack(el, [...keys], target);
          });
        }
      };
      menuTree.value?.forEach((el: RouteRecordRaw) => {
        if (isFind) return; // Performance optimization
        backtrack(el, [el.name as string], name);
      });
      return result;
    };

    // 监听路由变化
    listenerRouteChange((newRoute) => {
      const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta;
      // if (requiresAuth && (!hideInMenu || activeMenu)) {
      //   const menuOpenKeys = findMenuOpenKeys(
      //     (activeMenu || newRoute.name) as string
      //   );

      if (!hideInMenu || activeMenu) {
        const menuOpenKeys = findMenuOpenKeys(
          (activeMenu || newRoute.name) as string
        );

        const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
        openKeys.value = [...keySet];

        selectedKey.value = [
          activeMenu || menuOpenKeys[menuOpenKeys.length - 1]
        ];
      }
    }, true);
    const setCollapse = (val: boolean) => {
      if (appStore.device === 'desktop')
        appStore.updateSettings({ menuCollapse: val });
    };

    // 路由菜单渲染
    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach((element: any) => {
            let node;
            // This is demo, modify nodes as needed
            if (element.meta?.hideInMenu !== true) {
              const icon = element?.meta?.icon
                ? () => (
                    <IconFont type={element?.meta?.icon} size={20}></IconFont>
                  )
                : // h(compile(`<icon-font type='${element?.meta?.icon}'/>`))
                  null;
              node =
                element?.children && element?.children.length !== 0 ? (
                  <a-sub-menu
                    key={element.name}
                    v-slots={{
                      icon,
                      title: () => h(compile(element?.meta?.locale || ''))
                    }}
                  >
                    {travel(element?.children)}
                  </a-sub-menu>
                ) : (
                  <a-menu-item
                    key={element.name}
                    v-slots={{ icon }}
                    onClick={() => goto(element)}
                  >
                    {element?.meta?.locale}
                  </a-menu-item>
                );
              nodes.push(node as never);
            }
          });
        }
        return nodes;
      }
      return travel(menuTree.value);
    };

    const MenuClick = (key: any) => {
      if (key === 'WorkPlace') {
        menusStore.setCurrMenus('home');
        // sessionStorage.getItem('currMenus')
      }
      // if (sessionStorage.getItem('currMenus')) {
      //   let currMenusKey = JSON.parse(sessionStorage.getItem('currMenus') as any).meta.key;
      //   sessionStorage.setItem('currMenusKey', currMenusKey);
      // }
      // console.log(sessionStorage.getItem('currMenusKey'));
    };

    return () => (
      <div>
        <a-scrollbar style="height:calc(100vh - 120px - 50px);overflow: auto;min-width:90px">
          <a-menu
            v-model:collapsed={collapsed.value}
            v-model:open-keys={openKeys.value}
            show-collapse-button={appStore.device !== 'mobile'}
            auto-open={false}
            selected-keys={selectedKey.value}
            auto-open-selected={true}
            level-indent={34}
            style="height: 100%;"
            onCollapse={setCollapse}
            onMenuItemClick={MenuClick}
            collapsed-width={90}
            v-slots={{
              trigger: () =>
                h(
                  compile(
                    collapsed.value ? <IconCaretRight /> : <IconCaretLeft />
                  )
                )
            }}
          >
            {' '}
            {renderSubMenu()}
          </a-menu>
        </a-scrollbar>
      </div>
    );
  }
});
</script>

<style lang="less" scoped>
.arco-menu-collapsed {
  width: 90px;
}
:deep(.arco-menu-inner) {
  // background-color: #e9ebf9;
  color: #4e5969;
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
  }

  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }
}
:deep(.arco-menu-selected),
:deep(.arco-menu-item:hover),
:deep(.arco-menu-inline-header.arco-menu-selected.arco-menu-has-icon:hover),
:deep(.arco-menu-item.arco-menu-selected.arco-menu-has-icon),
:deep(.arco-menu-item.arco-menu-selected),
:deep(.arco-menu-pop.arco-menu-pop-header.arco-menu-has-icon:hover),
:deep(.arco-menu-inline-header:hover) {
  background-color: #f5f7fe !important;
}
:deep(.arco-menu-pop.arco-menu-pop-header.arco-menu-has-icon),
:deep(.arco-menu-item),
:deep(.arco-menu-inline-header) {
  // background-color: #e9ebf9 !important;
}
</style>
